package com.chongaizhen.sharding.code.configuration;

import java.util.Collection;
import java.util.Objects;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义分片策略
 */
@Slf4j
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     * collection 被查到的库列表
     * preciseShardingValue 分片列的值
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        log.info("collection: {}, preciseShardingValue: {}", JSON.toJSONString(collection),
                JSON.toJSONString(preciseShardingValue));
        for (String name : collection) {
            if (name.endsWith(String.valueOf(Math.abs(Objects.hash(preciseShardingValue.getValue())) % collection.size()))) {
                log.info("return name: {}", name);
                return name;
            }
        }
        return null;
    }
}